<?php

namespace App\Jobs;

use App\Models\User\WxUser;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\SafeUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class UserInputSafeCheckJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $user_id = 0;
    protected $check_string ='';
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($user_id, $check_string)
    {
        //
        $this->user_id = $user_id;
        $this->check_string = strtolower(strip_tags(htmlspecialchars_decode($check_string)));
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if($this->user_id && $this->check_string){
            $user_state = UserUtils::get_user_state($this->user_id, true);
            if($user_state == 2){
                return;
            }
            $is_sql_injection = SafeUtils::is_sql_injection($this->check_string);
            if($is_sql_injection){
                $times = get_user_meta($this->user_id, 'sql_injection_times', 'n') ?? 0;
                if($times >= 2){
                    $the_user = WxUser::find($this->user_id);
                    $r = UserUtils::lock_user_incre($the_user, 2, 3600 * 24 * 90, '疑似多次提交sql注射代码，被系统检测作出封号处理');
                    if($r){
                        update_user_meta($this->user_id, 'reason_for_sealing', '有'.($times + 1).'次疑似恶意提交sql注射代码记录', 's');
                        update_user_meta($this->user_id, 'sql_injection_times', $times + 1, 'n');
                        UserUtils::add_user_notice(1002, $this->user_id, '封号通知', '您疑似多次提交sql注射代码，被系统检测作出封号处理，若有疑问，请您联系客服', 100);
                        GatewayUtils::error_message(GatewayUtils::uid2client_id($this->user_id), '您疑似多次提交sql注射代码，被系统检测作出封号处理，若有疑问，请您联系客服');
                    }
                }else{
                    update_user_meta($this->user_id, 'sql_injection_times', $times + 1, 'n');
                }
            }
        }
    }
}
